<template>
  <!--导入对话框 -->
  <el-dialog
    :title="props.upload.title"
    v-model="props.upload.open"
    width="400px"
    append-to-body
  >
    <el-upload
      ref="uploadRef"
      :limit="1"
      :accept="fileType"
      :headers="headers"
      :action="props.upload.url + '?override=' + props.upload.override"
      :disabled="props.upload.disable"
      :before-upload="handleBeforeUpload"
      :on-progress="handleUploadProgress"
      :on-success="handleUploadSuccess"
      :auto-upload="false"
      drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="props.upload.override" />更新已存在的数据
          </div>
          <span
            >仅允许导入<b style="color: #f56c6c">{{ fileType }}</b
            >格式文件。
          </span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="downloadTemplate"
            >下载模板</el-link
          >
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="props.upload.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="YImport">
import { getToken, tokenKey } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["sumbited"]);

// 设置上传的请求头部
const headers = { Authorization: "Bearer " + getToken(tokenKey.access) };

const props = defineProps({
  upload: {
    type: Object,
    default: function () {
      return {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        disable: false,
        // 是否更新已经存在的字段数据
        override: true,
        // 上传的地址
        url: import.meta.env.VITE_APP_BASE_API + "",
        // 模板地址
        temp_url: "",
        // 下载后保存的模板名称
        temp_name: "template",
      };
    },
  },
  // 文件类型, 例如".json,.doc,.docx,.xls,.xlsx,.csv,.ppt,.xml,.txt,.pdf"
  fileType: {
    type: String,
    default: ".json,.xlsx,.xls,.csv",
  },
});

/** 下载模板操作 */
function downloadTemplate() {
  let url = props.upload.temp_url;
  let name = props.upload.temp_name;
  proxy.download("sys/file/download/", `${name}_${new Date().getTime()}.xlsx`, {
    url,
  });
}

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split(".");
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType}格式文件!`);
      return false;
    }
  }
  return true;
}

/**文件上传中处理 */
const handleUploadProgress = (event, file, fileList) => {
  props.upload.disable = true;
};

/** 文件上传成功处理 */
const handleUploadSuccess = (res, file, fileList) => {
  props.upload.open = false;
  props.upload.disable = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  if (res.code == 200) {
    proxy.$modal.msgSuccess("导入成功");
    emit("submited");
  } else {
    proxy.$modal.msgError(`导入失败，${JSON.stringify(res.msg)}`);
  }
};

/** 提交上传文件 */
function submit() {
  proxy.$refs["uploadRef"].submit();
}
</script>
